<template>
  <div>
    <div class="login" v-loading="loading">
      <div class="middle">
        <div class="left"></div>
        <div class="right">
          <div class="title">欢迎使用中健荟通管理系统</div>
          <div class="entitle">Welcome to the management system</div>
          <el-form
            :model="loginForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="" prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="用户名/邮箱地址"
              ></el-input>
            </el-form-item>
            <el-form-item label="" prop="psw">
              <el-input
                show-password
                v-model="loginForm.psw"
                placeholder="密码"
              ></el-input>
            </el-form-item>

            <div class="submit">
              <el-button
                type="primary"
                @keyup.enter="handleSubmit"
                @click="handleSubmit"
                >登录</el-button
              >
              <div class="forgetPsw hand_cs">忘记密码？</div>
            </div>
          </el-form>
        </div>
      </div>
    </div>
    <el-dialog
      title="管理员授权"
      :visible.sync="dialogVisible"
      width="500px"
      @close="closeDialog"
    >
      <div class="dialog_content">
        <div class="con">
          <vue-qr
            ref="Qrcode"
            :logo-src="logoSrc"
            :size="size"
            :margin="0"
            :text="qrUrl"
            :logoScale="0.2"
            :logoMargin="5"
          />
          <div class="manlte" v-if="timeout" @click="handleRefresh">
            <div>二维码已过期</div>
            <div class="refresh hand_cs">点击刷新</div>
          </div>
        </div>
        <div class="process" v-if="!timeout">
          <el-progress :stroke-width="6" :percentage="percentage"></el-progress>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import VueQr from "vue-qr";
import { userLogin, scanQr } from "@/api/login";
import md5 from "js-md5";
export default {
  name: "QrCode",
  components: {
    VueQr,
  },
  data() {
    return {
      loading: false,
      loginForm: {
        username: "",
        psw: "",
        code: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        psw: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },

      dialogVisible: false,
      qrUrl: "www.baidu.com",
      percentage: 0,
      logoSrc: require("@/assets/logo.png"), // 二维码中间logo图片（选填）
      size: 140, // 二维码尺寸（选填）
      timer: null,
      timeout: false,
    };
  },
  methods: {
    async userLogin() {
      const { data, err, msg } = await userLogin({
        username: this.loginForm.username,
        pass: md5(this.loginForm.psw),
      });
      if (err === 0) {
        sessionStorage.setItem("token", data.token);
        sessionStorage.setItem("username", data.nick);
        sessionStorage.setItem("expire_time", data.expire_time);
        // this.$message({
        //   showClose: true,
        //   message: "登录成功！",
        //   type: "success",
        // });
        this.$notify({
          type: "success",
          message: "登录成功",
          duration: 1500,
        });
        //路由处理 成功跳转
        //先获取菜单  处理路由后添加至router里面
        this.$router.push("/");
        // this.qrUrl = data.qr_code;
        // this.dialogVisible = true;
        // this.timeout = false;
        // this.timer = setInterval(() => {
        //   this.scanQr(data.encrypt_key, data.request_id);
        // }, 1000);
      } else {
        this.loading = false;
        this.$message({
          showClose: true,
          message: `${msg}`,
          type: "error",
        });
      }
    },

    async scanQr(encrypt_key, request_id) {
      const { data, err } = await scanQr({
        encrypt_key,
        request_id,
      });
      if (err === 0) {
        //成功
        this.cleartime();
        this.$message.success({
          showClose: true,
          message: "登录成功",
        });
        sessionStorage.setItem("token", data.token);
        this.percentage = 100;
        setTimeout(() => {
          this.$router.push("/");
        }, 500);
      } else if (err === 10501) {
        //二维码过期
        this.timeout = true;
        this.cleartime();
      } else if (err === 10502) {
        //继续等待二维码验证
        // this.percentage = Number(data.process);
        switch (Number(data.process)) {
          case 1:
            this.percentage = 33.33;
            break;
          case 2:
            this.percentage = 66.66;
            break;
          default:
            this.percentage = 0;
            break;
        }
      }
    },
    //关闭弹窗
    closeDialog() {
      this.cleartime();
    },
    handleSubmit() {
      //验证
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.userLogin();
        } else {
          return false;
        }
      });
      //登录进行二维码验证
    },
    //点击刷新
    handleRefresh() {
      this.userLogin();
    },
    cleartime() {
      clearInterval(this.timer);
      this.timer = null;
    },
    // // 点击回车键登录
    keyDown(e) {
      // 回车则执行登录方法 enter键的ASCII是13
      if (e.keyCode === 13) {
        this.handleSubmit(); // 定义的登录方法
      }
    },
  },
  mounted() {
    // 绑定监听事件
    window.addEventListener("keydown", this.keyDown);
  },
  destroyed() {
    // 销毁事件
    window.removeEventListener("keydown", this.keyDown, false); //销毁回车事件，如果不销毁，在其他页面敲回车也会执行回车登录操作。
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
  },
  created() {
    sessionStorage.clear();
  },
};
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("@/assets/bg.png") no-repeat;
  background-size: 100% 100%;
  background-position: 100% 100%;
  .middle {
    width: 50%;
    height: 60%;
    display: flex;
    box-shadow: 0px 0px 35px 0px rgba(10, 109, 217, 0.14);
    border-radius: 4px;
    background-color: #fff;
    .left {
      width: 45%;
      height: 100%;
      background: url("@/assets/left.png") no-repeat;
      background-size: 100% 100%;
      background-position: 100% 100%;
      background-color: #f2f7fd;
      border-radius: 4px 0 0 4px;
    }
    .right {
      flex: 1;
      padding: 0 60px;
      box-sizing: border-box;
      //   margin-left: 100px;
      .forgetPsw {
        font-size: 12px;
        margin-top: 20px;
      }
      .content {
        margin: 0 auto;
      }
      .title {
        text-align: left;
        padding-top: 30px;
        box-sizing: border-box;
        font-size: 24px;
        color: #333333;
      }
      .entitle {
        text-align: start;
        font-size: 16px;
        margin: 20px 0;
      }
      .demo-ruleForm {
        margin-top: 55px;
      }
      .el-form-item__label {
        width: 100%;
      }
      /deep/.el-form-item__label {
        width: 100% !important;
        text-align: start !important;
      }
      /deep/.el-form-item__content {
        margin-left: 0 !important;
      }
      .submit {
        text-align: start;
        .el-button {
          width: 100%;
        }
      }
      .el-button {
        padding: 12px 50px;
      }
      .el-form-item {
        margin-bottom: 22px;
      }
    }
  }
}
/deep/.el-dialog__header {
  padding-top: 40px;
  box-sizing: border-box;
}
/deep/.el-dialog__title {
  font-weight: bold;
}
.process {
  margin: 30px 0 0;
}
.con {
  position: relative;
  .manlte {
    position: absolute;
    width: 100%;
    height: 100%;
    top: -2px;
    left: 0;
    background-color: rgba(255, 255, 255, 0.6);
    backdrop-filter: blur(2px);
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    color: rgba($color: #000, $alpha: 0.8);
    font-size: 16px;
    .refresh {
      margin-top: 10px;
      color: rgb(98, 107, 209);
    }
  }
}
::v-deep .el-dialog__body {
  padding-top: 0;
  min-height: 279px;
  display: flex;
  align-items: center;
  justify-content: center;
  .dialog_content {
    width: 100%;
  }
}
</style>
